package study.alex.resumedb.gae;

import com.vaadin.server.StreamResource;

import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: alex
 * Date: 05.02.14
 * Time: 9:53
 * SVN $Id$
 */
public class ImageResource implements StreamResource.StreamSource, Serializable {
    private ByteArrayOutputStream imagebuffer = null;
    private RenderedImage renderedImage = null;

    public ImageResource(RenderedImage image) {
        this.renderedImage = image;
    }

    public InputStream getStream () {
        /* Create an image and draw something on it. */
        if (renderedImage != null) {
            try {
                /* Write the image to a buffer. */
                imagebuffer = new ByteArrayOutputStream();
                ImageIO.write(renderedImage, "png", imagebuffer);

                /* Return a stream from the buffer. */
                return new ByteArrayInputStream(
                        imagebuffer.toByteArray());
            } catch (IOException e) {
                Logger.getLogger(ImageResource.class.getName()).fine("Can't create stream from graphics.\n" + e.getMessage());
                return null;
            }
        }
        Logger.getLogger(ImageResource.class.getName()).fine("Nothing to do: null graphics");
        return null;
    }
}
